package com.laikan.reader.bookstore.view;

/**
 * @author wx 当前类用于精选页面的滑动 暴露出来的接口有：
 * @category 修改头部文字，但不从新加载适配器
 * @category 修改头部字体样式（文字大小 间距 居上下左右的距离）
 * @category 保存当前记录状态（保存状态可在viewpage的监听事件操作）
 * @category viewpage存在的缺陷，在滑动的时候的偏移量是0
 * -1，不滑动的时候为0，但是当操作随意滑动的时候，viewpage随之的偏移量无法重置为0，需要手动设置
 * @category 提供修改滑动线的高度，宽度
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.umeng.analytics.MobclickAgent;

import java.util.Locale;

public class PagerSlidingTabStrip extends HorizontalScrollView {

    private static final int[] ATTRS = new int[]{android.R.attr.textSize, android.R.attr.textColor};
    private final PageListener pageListener = new PageListener();
    public OnPageChangeListener delegatePageListener;
    private LinearLayout.LayoutParams defaultTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;
    private LinearLayout tabsContainer;
    private ViewPager pager;
    private int tabCount;
    private int currentPosition = 0;
    private float currentPositionOffset = 0f;
    private Paint rectPaint;
    private Paint dividerPaint;
    private int indicatorColor = getResources().getColor(R.color.C_FF3F9FE0);
    private int underlineColor = 0x1A000000;
    private int dividerColor = 0x1A000000;
    private boolean shouldExpand = false;
    private boolean textAllCaps = true;
    private int padding_Bottom_Top = 22;
    private int scrollOffset = 52;
    private int indicatorHeight = 2;
    private int underlineHeight = 2;
    private int dividerPadding = 12;
    private int tabPadding = 0;
    private int dividerWidth = 1;
    private int tabTextSize = 15;
    private int tabTextColor = 0xFF666666;
    private Typeface tabTypeface = null;
    private int tabTypefaceStyle = Typeface.NORMAL;
    private int lastScrollX = 0;
    private int tabBackgroundResId = -1;
    private Locale locale;
    private int width;
    private String[] book = null;
    private boolean isRefresh = false;

    public PagerSlidingTabStrip(Context context) {
        this(context, null);
    }

    public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        setFillViewport(true);
        setWillNotDraw(false);
        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        addView(tabsContainer);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        scrollOffset = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
        indicatorHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
        underlineHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
        dividerPadding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
        tabPadding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
        dividerWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
        tabTextSize = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
        TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
        tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
        tabTextColor = a.getColor(1, tabTextColor);
        a.recycle();
        a = context.obtainStyledAttributes(attrs, R.styleable.BookShelfPagerSlidingTabStrip);
        indicatorColor = a.getColor(R.styleable.BookShelfPagerSlidingTabStrip_pstsIndicatorColor, indicatorColor);
        underlineColor = a.getColor(R.styleable.BookShelfPagerSlidingTabStrip_pstsUnderlineColor, underlineColor);
        dividerColor = a.getColor(R.styleable.BookShelfPagerSlidingTabStrip_pstsDividerColor, dividerColor);
        indicatorHeight = a.getDimensionPixelSize(R.styleable.BookShelfPagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight);
        underlineHeight = a.getDimensionPixelSize(R.styleable.BookShelfPagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight);
        dividerPadding = a.getDimensionPixelSize(R.styleable.BookShelfPagerSlidingTabStrip_pstsDividerPadding, dividerPadding);
        tabPadding = a.getDimensionPixelSize(R.styleable.BookShelfPagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding);
        tabBackgroundResId = a.getResourceId(R.styleable.BookShelfPagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId);
        shouldExpand = a.getBoolean(R.styleable.BookShelfPagerSlidingTabStrip_pstsShouldExpand, shouldExpand);
        scrollOffset = a.getDimensionPixelSize(R.styleable.BookShelfPagerSlidingTabStrip_pstsScrollOffset, scrollOffset);
        textAllCaps = a.getBoolean(R.styleable.BookShelfPagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);
        a.recycle();
        rectPaint = new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Style.FILL);
        dividerPaint = new Paint();
        dividerPaint.setAntiAlias(true);
        dividerPaint.setStrokeWidth(dividerWidth);
        defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);

        if (locale == null) {
            locale = getResources().getConfiguration().locale;
        }
    }

    /**
     * 设置viewpage 并添加监听
     *
     * @param pager
     * @param context
     * @param str
     */
    public void setViewPager(ViewPager pager, Context context, String[] str) {
        this.pager = pager;
        book = str;
        if (pager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        if (SPUtil.getBoolean("refresh_tab", false)) {
            currentPosition = 4;
        }
        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        pager.setOnPageChangeListener(pageListener);
        notifyDataSetChanged();
    }

    public void setOnPageChangeListener(OnPageChangeListener listener) {
        this.delegatePageListener = listener;
    }

    /**
     * 修改头部加载文字，但不重新加载viewpage的适配器。
     */
    public void notifyDataSetChanged() {

        tabsContainer.removeAllViews();

        tabCount = pager.getAdapter().getCount();

        for (int i = 0; i < 5; i++) {
            if (pager.getAdapter() instanceof IconTabProvider) {
                addIconTab(i, ((IconTabProvider)pager.getAdapter()).getPageIconResId(i));
            }else {
                addTextTab(i, book[i]);
            }

        }

        updateTabStyles();
        if (!isRefresh) {
            scrollToChild(currentPosition, 0);
            isRefresh = true;
        }
        currentPositionOffset = 0f;

    }

    private void addTextTab(final int position, String title) {

        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();

        addTab(position, tab);
    }

    private void addIconTab(final int position, int resId) {

        ImageButton tab = new ImageButton(getContext());
        tab.setImageResource(resId);

        addTab(position, tab);

    }

    private void addTab(final int position, View tab) {

        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pager.setCurrentItem(position);
                changeTextColor(position);
            }
        });

        LinearLayout.LayoutParams sp_params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        sp_params.width = width / 5;
        tab.setPadding(0, padding_Bottom_Top, 0, padding_Bottom_Top);
        tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : sp_params);
    }

    // 字体变色
    public void changeTextColor(int position) {
        addUMengVital(position);
        for (int i = 0; i < 5; i++) {
            TextView text = (TextView)tabsContainer.getChildAt(i);
            if (i == position) {
                text.setTextColor(Color.parseColor("#66ccdd"));
            }else {
                text.setTextColor(Color.GRAY);
            }
        }
    }

    /**
     * 添加友盟统计
     */
    private void addUMengVital(int position){

        if(SPUtil.getInt("select_setting", 0)==1){
            if(position ==0){
                MobclickAgent.onEvent(getContext(), "bookstore_m_sec_recommend");
            }else if(position ==1){
                MobclickAgent.onEvent(getContext(), "bookstore_m_sec_free");
            }else if(position ==2){
                MobclickAgent.onEvent(getContext(), "bookstore_m_sec_rank");
            }else if(position ==3){
                MobclickAgent.onEvent(getContext(), "bookstore_m_sec_class");
            }else if(position ==4){
                MobclickAgent.onEvent(getContext(), "bookstore_m_sec_end");

            }
        }else if(SPUtil.getInt("select_setting", 0)==2){

            if(position ==0){
                MobclickAgent.onEvent(getContext(), "bookstore_w_sec_recommend");
            }else if(position ==1){
                MobclickAgent.onEvent(getContext(), "bookstore_w_sec_free");
            }else if(position ==2){
                MobclickAgent.onEvent(getContext(), "bookstore_w_sec_rank");
            }else if(position ==3){
                MobclickAgent.onEvent(getContext(), "bookstore_w_sec_class");
            }else if(position ==4){
                MobclickAgent.onEvent(getContext(), "bookstore_w_sec_end");

            }
        }else if(SPUtil.getInt("select_setting", 0)==3){

            if(position ==0){
                MobclickAgent.onEvent(getContext(), "bookstore_p_sec_recommend");
            }else if(position ==1){
                MobclickAgent.onEvent(getContext(), "bookstore_p_sec_free");
            }else if(position ==2){
                MobclickAgent.onEvent(getContext(), "bookstore_p_sec_rank");
            }else if(position ==3){
                MobclickAgent.onEvent(getContext(), "bookstore_p_sec_class");
            }else if(position ==4){
                MobclickAgent.onEvent(getContext(), "bookstore_p_sec_end");

            }
        }
    }
    /**
     * 更改头部字体样式
     */
    private void updateTabStyles() {

        for (int i = 0; i < tabCount; i++) {
            View v = tabsContainer.getChildAt(i);

            if (tabBackgroundResId > 0) {
                v.setBackgroundResource(tabBackgroundResId);
            }
            if (v instanceof TextView) {

                TextView tab = (TextView)v;
                tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
                tab.setTypeface(tabTypeface, tabTypefaceStyle);
                if (i == currentPosition) {
                    tab.setTextColor(Color.parseColor("#66ccdd"));
                }else {
                    tab.setTextColor(Color.GRAY);
                }
                if (textAllCaps) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        tab.setAllCaps(true);
                    }else {
                        tab.setText(tab.getText().toString().toUpperCase(locale));
                    }
                }
            }
        }

    }

    private void scrollToChild(int position, int offset) {

        if (tabCount == 0) {
            return;
        }

        int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;

        if (position > 0 || offset > 0) {
            newScrollX -= scrollOffset;
        }

        if (newScrollX != lastScrollX) {
            lastScrollX = newScrollX;
            scrollTo(newScrollX, 0);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isInEditMode() || tabCount == 0) {
            return;
        }

        final int height = getHeight();
        rectPaint.setColor(Color.parseColor("#66ccdd"));
        View currentTab = tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();

        if (currentPositionOffset > 0f && currentPosition < 4) {
            View nextTab = tabsContainer.getChildAt(currentPosition + 1);
            final float nextTabLeft = nextTab.getLeft();
            final float nextTabRight = nextTab.getRight();

            lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
            lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);

        }

        canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);

        // draw underline
        // rectPaint.setColor(underlineColor);
        // canvas.drawRect(0, height - underlineHeight,
        // tabsContainer.getWidth(), height, rectPaint);
        // draw divider
        // dividerPaint.setColor(dividerColor);
        // for (int i = 0; i < tabCount - 1; i++) {
        // View tab = tabsContainer.getChildAt(i);
        // canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(),
        // height - dividerPadding, dividerPaint);
        // }
    }

    public void setIndicatorColorResource(int resId) {
        this.indicatorColor = getResources().getColor(resId);
        invalidate();
    }

    public int getIndicatorColor() {
        return this.indicatorColor;
    }

    public void setIndicatorColor(int indicatorColor) {
        this.indicatorColor = indicatorColor;
        invalidate();
    }

    public void setIndicators(String[] str) {
        this.book = str;
        pager.setCurrentItem(currentPosition);
        notifyDataSetChanged();

    }

    public int getIndicatorHeight() {
        return indicatorHeight;
    }

    public void setIndicatorHeight(int indicatorLineHeightPx) {
        this.indicatorHeight = indicatorLineHeightPx;
        invalidate();
    }

    public void setUnderlineColorResource(int resId) {
        this.underlineColor = getResources().getColor(resId);
        invalidate();
    }

    public int getUnderlineColor() {
        return underlineColor;
    }

    public void setUnderlineColor(int underlineColor) {
        this.underlineColor = underlineColor;
        invalidate();
    }

    public void setDividerColorResource(int resId) {
        this.dividerColor = getResources().getColor(resId);
        invalidate();
    }

    public int getDividerColor() {
        return dividerColor;
    }

    public void setDividerColor(int dividerColor) {
        this.dividerColor = dividerColor;
        invalidate();
    }

    public int getUnderlineHeight() {
        return underlineHeight;
    }

    public void setUnderlineHeight(int underlineHeightPx) {
        this.underlineHeight = underlineHeightPx;
        invalidate();
    }

    public int getDividerPadding() {
        return dividerPadding;
    }

    public void setDividerPadding(int dividerPaddingPx) {
        this.dividerPadding = dividerPaddingPx;
        invalidate();
    }

    public int getScrollOffset() {
        return scrollOffset;
    }

    public void setScrollOffset(int scrollOffsetPx) {
        this.scrollOffset = scrollOffsetPx;
        invalidate();
    }

    public boolean getShouldExpand() {
        return shouldExpand;
    }

    public void setShouldExpand(boolean shouldExpand) {
        this.shouldExpand = shouldExpand;
        requestLayout();
    }

    public boolean isTextAllCaps() {
        return textAllCaps;
    }

    public void setAllCaps(boolean textAllCaps) {
        this.textAllCaps = textAllCaps;
    }

    public int getTextSize() {
        return tabTextSize;
    }

    public void setTextSize(int textSizePx) {
        this.tabTextSize = textSizePx;
        updateTabStyles();
    }

    public void setTextColorResource(int resId) {
        this.tabTextColor = getResources().getColor(resId);
        updateTabStyles();
    }

    public int getTextColor() {
        return tabTextColor;
    }

    public void setTextColor(int textColor) {
        this.tabTextColor = textColor;
        updateTabStyles();
    }

    public void setTypeface(Typeface typeface, int style) {
        this.tabTypeface = typeface;
        this.tabTypefaceStyle = style;
        updateTabStyles();
    }

    public int getTabBackground() {
        return tabBackgroundResId;
    }

    public void setTabBackground(int resId) {
        this.tabBackgroundResId = resId;
    }

    public int getTabPaddingLeftRight() {
        return tabPadding;
    }

    public void setTabPaddingLeftRight(int paddingPx) {
        this.tabPadding = paddingPx;
        updateTabStyles();
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState)state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.currentPosition;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPosition = currentPosition;
        return savedState;
    }

    public interface IconTabProvider {

        int getPageIconResId(int position);
    }

    static class SavedState extends BaseSavedState {

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
        int currentPosition;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPosition);
        }
    }

    private class PageListener implements OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            currentPosition = position;
            currentPositionOffset = positionOffset;

            scrollToChild(position, (int)(positionOffset * tabsContainer.getChildAt(position).getWidth()));

            invalidate();

            if (delegatePageListener != null) {
                delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
//                scrollToChild(pager.getCurrentItem(), 0);
                changeTextColor(pager.getCurrentItem());
//                currentPosition = pager.getCurrentItem();
            }
            if (delegatePageListener != null) {
                delegatePageListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (delegatePageListener != null) {
                delegatePageListener.onPageSelected(position);
                changeTextColor(pager.getCurrentItem());
            }
        }

    }

}
